package com.ezjie.ielts.core.http;

import java.io.File;
import java.util.Map;

import android.content.Context;

import com.alibaba.fastjson.JSONObject;
import com.ezjie.ielts.core.base.HttpHeaderBean;
import com.ezjie.ielts.db.UserInfoDB;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.SystemUtils;
import com.ezjie.login.model.UserDetail;
import com.igexin.sdk.PushManager;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * Http请求类
 * 
 * @author renyangyang
 *
 */
public class HttpAPI {
	/** 设置超时时间 */
	private static final int TIME_OUT = 1000 * 0;
	private static final boolean USESSL = false;

	private static HttpAPI httpUtil;

	private final HttpUtils http = new HttpUtils();

	private static String mApiBaseUrl;
	private static Context mContext;

	public static String getScheme() {
		return USESSL ? "https://" : "http://";
	}

	private HttpAPI(Context context) {
		super();

	}

	public static HttpAPI getInstance(Context context) {
		mContext = context;
		mApiBaseUrl = getScheme() + ServerInterfaceDefinition.API_BASE;
		if (httpUtil == null) {
			httpUtil = new HttpAPI(context);
		}
		return httpUtil;
	}

	/**
	 * 用户接口域名
	 * 
	 * @param context
	 * @param isUserDomain
	 * @return
	 */
	public static HttpAPI getInstance(Context context, boolean isUserDomain) {
		mContext = context;
		if (isUserDomain) {
			mApiBaseUrl = getScheme() + ServerInterfaceDefinition.API_USER_BASE;
		} else {
			mApiBaseUrl = getScheme() + ServerInterfaceDefinition.API_BASE;
		}

		if (httpUtil == null) {
			httpUtil = new HttpAPI(context);
		}
		return httpUtil;
	}

	private RequestParams assemblyGetRequestParams(Map<String, String> params) {
		RequestParams requestParams = new RequestParams();

		requestParams.addHeader("parameters", requestParameters());
		if (params != null) {
			if (!params.isEmpty()) {
				for (Map.Entry<String, String> entry : params.entrySet()) {// 构建表单字段内容
					LogUtils.d("Param: " + entry.getKey() + ":" + entry.getValue());
					requestParams.addQueryStringParameter(entry.getKey(),
							entry.getValue() == null ? "" : entry.getValue());
				}
			}
		}
		return requestParams;
	}

	private RequestParams assemblyPostRequestParams(Map<String, String> params, Map<String, File> files) {
		RequestParams requestParams = new RequestParams();
		requestParams.addHeader("parameters", requestParameters());
		if (params != null) {
			if (!params.isEmpty()) {
				for (Map.Entry<String, String> entry : params.entrySet()) {// 构建表单字段内容
					LogUtils.d("Param: " + entry.getKey() + ":" + entry.getValue());
					requestParams.addBodyParameter(entry.getKey(), entry.getValue() == null ? "" : entry.getValue());
				}
			}
		}

		if (files != null) {
			if (!files.isEmpty()) {
				for (Map.Entry<String, File> entry : files.entrySet()) {// 构建表单字段内容

					LogUtils.d("Param: " + entry.getKey() + ":" + entry.getValue());

					requestParams.addBodyParameter(entry.getKey(), entry.getValue());
				}
			}
		}

		return requestParams;
	}

	public String requestCookieKey() {
		StringBuilder sb = new StringBuilder();

		try {
			sb.append("app_version=").append(SystemUtils.getVersion(mContext)).append(";system_version=")
					.append(SystemUtils.getSystemVersion()).append(";system=").append("Android").append(";device=")
					.append(SystemUtils.getBrand(mContext)).append(";device_id=").append(SystemUtils.getIMEI(mContext))
					.append(";nationality=").append(mContext.getResources().getConfiguration().locale.getCountry())
					.append(";Accept-Language=").append(SystemUtils.getLanguage());

			LogUtils.d("cookie:" + sb.toString());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();
	}

	public String requestParameters() {
		UserInfoDB userInfoDB = new UserInfoDB(mContext);
		UserDetail userDetail = userInfoDB.queryLoginUser();
		HttpHeaderBean headerBean = new HttpHeaderBean();
		headerBean.setApp_name("ezjie.android.ieltsezj");
		headerBean.setApp_version(SystemUtils.getVersion(mContext));
		headerBean.setCid(PushManager.getInstance().getClientid(mContext));
		headerBean.setDevice(SystemUtils.getBrand(mContext));
		headerBean.setDevice_id(SystemUtils.getIMEI(mContext));
		headerBean.setDevice_token("");
		headerBean.setLogin_key(userDetail.login_key);
		headerBean.setNationality(mContext.getResources().getConfiguration().locale.getCountry());
		headerBean.setSystem("Android");
		headerBean.setSystem_version(SystemUtils.getSystemVersion());
		headerBean.setUid(userDetail.uid);
		headerBean.setVersion_code(SystemUtils.getVersionCode(mContext));

		String jsonStr = JSONObject.toJSON(headerBean).toString();
		LogUtils.d("parameters:" + jsonStr);
		return jsonStr;
	}

	private String fullUrl(String url) {
		return mApiBaseUrl + url;

	}

	/**
	 * 发送GET请求
	 * 
	 * @param path
	 * @param params
	 * @param httpRequestCallback
	 */
	public HttpHandler<String> doGetRequest(String path, Map<String, String> params,
			final HttpRequestCallBack httpRequestCallback) {
		http.configCurrentHttpCacheExpiry(TIME_OUT);// 设置超时时间
		LogUtils.d(fullUrl(path));
		return http.send(HttpMethod.GET, fullUrl(path), assemblyGetRequestParams(params),
				new RequestCallBack<String>() {// 接口回调
					@Override
					public void onStart() {
						httpRequestCallback.onStartCallBack();
					}

					@Override
					public void onLoading(long total, long current, boolean isUploading) {
						httpRequestCallback.onLoadingCallBack(total, current, isUploading);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						httpRequestCallback.onFailureCallBack(error, msg);
					}

					@Override
					public void onSuccess(ResponseInfo<String> info) {
						httpRequestCallback.onSuccessCallBack(info.result);
					}
				});
	}

	/**
	 * 发送POST请求
	 * 
	 * @param path
	 * @param params
	 * @param httpRequestCallback
	 */
	public void doPostRequest(String path, Map<String, String> params, final HttpRequestCallBack httpRequestCallback) {
		http.configCurrentHttpCacheExpiry(TIME_OUT);// 设置超时时间
		LogUtils.d(fullUrl(path));

		http.send(HttpMethod.POST, fullUrl(path), assemblyPostRequestParams(params, null),
				new RequestCallBack<String>() {// 接口回调
					@Override
					public void onStart() {
						httpRequestCallback.onStartCallBack();
					}

					@Override
					public void onLoading(long total, long current, boolean isUploading) {
						httpRequestCallback.onLoadingCallBack(total, current, isUploading);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						httpRequestCallback.onFailureCallBack(error, msg);
						LogUtils.d(error.getExceptionCode() + "," + msg);
					}

					@Override
					public void onSuccess(ResponseInfo<String> info) {
						httpRequestCallback.onSuccessCallBack(info.result);
					}
				});
	}

	/**
	 * 发送DELETE请求
	 * 
	 * @param path
	 * @param params
	 * @param httpRequestCallback
	 */
	public void doDeleteRequest(String path, Map<String, String> params, final HttpRequestCallBack httpRequestCallback) {
		http.configCurrentHttpCacheExpiry(TIME_OUT);// 设置超时时间
		LogUtils.d(fullUrl(path));

		http.send(HttpMethod.DELETE, fullUrl(path), assemblyGetRequestParams(params), new RequestCallBack<String>() {// 接口回调
					@Override
					public void onStart() {
						httpRequestCallback.onStartCallBack();
					}

					@Override
					public void onLoading(long total, long current, boolean isUploading) {
						httpRequestCallback.onLoadingCallBack(total, current, isUploading);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						httpRequestCallback.onFailureCallBack(error, msg);
						LogUtils.d(error.getExceptionCode() + "," + msg);
					}

					@Override
					public void onSuccess(ResponseInfo<String> info) {
						httpRequestCallback.onSuccessCallBack(info.result);
					}
				});
	}

	/**
	 * 上传单个文件
	 * 
	 * @param path
	 * @param params
	 * @param files
	 * @param httpRequestCallback
	 */
	public void doUploadRequest(String path, RequestParams params, final HttpRequestCallBack httpRequestCallback) {
		http.configCurrentHttpCacheExpiry(TIME_OUT);// 设置超时时间
		LogUtils.d(fullUrl(path));

		http.send(HttpMethod.POST, fullUrl(path), params, new RequestCallBack<String>() {// 接口回调
					@Override
					public void onStart() {
						httpRequestCallback.onStartCallBack();
					}

					@Override
					public void onLoading(long total, long current, boolean isUploading) {
						httpRequestCallback.onLoadingCallBack(total, current, isUploading);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						httpRequestCallback.onFailureCallBack(error, msg);
					}

					@Override
					public void onSuccess(ResponseInfo<String> info) {
						httpRequestCallback.onSuccessCallBack(info.result);
					}
				});

	}

	/**
	 * 上传多个文件
	 * 
	 * @param path
	 * @param params
	 * @param files
	 * @param httpRequestCallback
	 */
	public void doUploadFileRequest(String path, Map<String, String> params, Map<String, File> files,
			final HttpRequestCallBack httpRequestCallback) {
		http.configCurrentHttpCacheExpiry(TIME_OUT);// 设置超时时间
		LogUtils.d(fullUrl(path));
		RequestParams requestParams = assemblyPostRequestParams(params, files);

		http.send(HttpMethod.POST, fullUrl(path), requestParams, new RequestCallBack<String>() {// 接口回调
					@Override
					public void onStart() {
						httpRequestCallback.onStartCallBack();
					}

					@Override
					public void onLoading(long total, long current, boolean isUploading) {
						httpRequestCallback.onLoadingCallBack(total, current, isUploading);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						httpRequestCallback.onFailureCallBack(error, msg);
					}

					@Override
					public void onSuccess(ResponseInfo<String> info) {
						httpRequestCallback.onSuccessCallBack(info.result);
					}
				});

	}

	/**
	 * 下载文件
	 * 
	 * @param path
	 * @param target
	 * @param httpRequestCallback
	 */
	public void doDownloadRequest(String path, String target, final RequestCallBack requestCallBack) {
		http.configCurrentHttpCacheExpiry(TIME_OUT);// 设置超时时间
		LogUtils.d(fullUrl(path));
		http.download(path, target, true, false, new RequestCallBack<File>() {

			@Override
			public void onStart() {
				requestCallBack.onStart();
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				requestCallBack.onFailure(arg0, arg1);

			}

			@Override
			public void onSuccess(ResponseInfo<File> arg0) {
				requestCallBack.onSuccess(arg0);
			}
		});

	}

}
